package libs

import (
	docker "github.com/fsouza/go-dockerclient"
	"io"
	"log"
)

const endpoint = "http://localhost:2375"

/*
	docker 运行命令
	cmd := []string{"ping", "-c", "10", "127.0.0.1"}
	err = libs.DockerRunCmd(os.Stdout,os.Stderr,os.Stdin,"c1c1f6efe737",cmd)
	if err != nil{
		fmt.Println(err)
	}
*/
func DockerRunCmd(OutputStream, ErrorStream io.Writer, InputStream io.Reader, Container string, cmd []string) error {
	client, err := docker.NewClient(endpoint)
	if err != nil {
		log.Fatal(err)
	}
	createOpts := docker.CreateExecOptions{
		Container:    Container,
		AttachStdin:  true,
		AttachStdout: true,
		AttachStderr: true,
		Tty:          true,
		//Cmd:          []string{"sh", "-c", "echo '\x21\x21' > /tmp/aaa2"},
		Cmd: cmd,
	}
	exec, err := client.CreateExec(createOpts)
	if err != nil {
		return err
	}

	// start exec
	//reader := strings.NewReader("ping www.baidu.com")
	//var stdout, stderr bytes.Buffer
	startOpts := docker.StartExecOptions{
		Detach:       false,
		OutputStream: OutputStream,
		ErrorStream:  ErrorStream,
		InputStream:  InputStream,
		RawTerminal:  false,
	}
	//go func() {
	err = client.StartExec(exec.ID, startOpts)
	if err != nil {
		return err
	}
	//}()
	//fmt.Println(stdout.String())
	//fmt.Println(stderr.String())
	return nil
}
